/**
 * 
 */
package furniture.viewer;

import java.io.IOException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * @author balage
 *
 */
public class ConvertFurnitureHandler extends AbstractHandler implements
		IHandler {

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection s = HandlerUtil.getCurrentSelection(event);
		
		if (s instanceof IStructuredSelection){
			Object o = ((IStructuredSelection) s).getFirstElement();
			if (o instanceof IFile){
				
				IFile src = (IFile)o;
				URI srcuri = URI.createPlatformResourceURI(src.getFullPath().toString(), true);
				URI outuri = srcuri.trimSegments(1).appendSegment(src.getName()+".furniture");
				
				ResourceSet rs = new ResourceSetImpl();
				Resource rsrc = rs.getResource(srcuri, true);
				Resource out = rs.createResource(outuri);
				
				out.getContents().addAll(rsrc.getContents());
				try {
					out.save(null);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}

}
